package com.lvan.excelhandle.listener;


import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.lvan.excelhandle.bean.StudentExcel;
import com.lvan.excelhandle.service.ExcelService;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Lvan
 * <p>
 * invoke：按行解析Excel中的内容（解析一行调用一次）
 * invokeHeadMap：解析Excel表头
 * doAfterAllAnalysed：Excel解析完成之后调用
 * </p>
 */
public class ExcelListener extends AnalysisEventListener<StudentExcel> {

    private ExcelService service;

    /**
     * 数据批量写入，每隔100条数据写入一次数据库
     */
    private static final int BATCH_COUNT = 3000;
    private List<StudentExcel> list = new ArrayList<>();

    public ExcelListener(ExcelService service) {
        this.service = service;
    }

    @Override
    public void invoke(StudentExcel student, AnalysisContext analysisContext) {
        if (student != null) {
            list.add(student);
            // 达到BATCH_COUNT量后立即入库，防止数据内存中数据过多，造成OOM
            if (list.size() >= BATCH_COUNT) {
                addStudentList(list);
                list.clear();
            }
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        addStudentList(list);
        list.clear();
    }

    private void addStudentList(List<StudentExcel> list) {
        service.addStudentList(list);
    }
}
